﻿using System;
using System.Web;
using System.Web.Security;
using mvcForum.Core;
using mvcForum.Core.Specifications;
using mvcForum.Web.Interfaces;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web.Providers {

	public class MVCForumUserProvider : IWebUserProvider {
		private readonly IRepository<ForumUser> userRepo;

		public MVCForumUserProvider(IRepository<ForumUser> userRepo) {
			this.userRepo = userRepo;
		}

		private ForumUser user;
		/// <summary>
		/// Get the authenticated user.
		/// </summary>
		public ForumUser ActiveUser {
			get {
				if (this.Authenticated) {
					return user;
				}
				return null;
			}
		}

		protected Boolean checkedAuthenticated = false;
		protected Boolean authenticated = false;
		/// <summary>
		/// Do we have an authenticated user?
		/// </summary>
		public Boolean Authenticated {
			get {
				if (!this.checkedAuthenticated) {
					if (HttpContext.Current != null && HttpContext.Current.User.Identity.IsAuthenticated) {
						MembershipUser u = System.Web.Security.Membership.GetUser(false);
						this.authenticated = (u != null);
						if (this.authenticated) {
							try {
								user = this.userRepo.ReadOne(new ForumUserSpecifications.SpecificProviderUserKey(u.ProviderUserKey.ToString()));
							}
							catch { }
							this.authenticated = (user != null);
						}
					}
					this.checkedAuthenticated = true;
				}
				return this.authenticated;
			}
		}
	}
}